package com.training.hatton.dropboxclient.processor.common;

import java.util.ArrayList;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.ResultReceiver;

import com.training.hatton.base.RequestDataWrapper;


public abstract class DropboxListModelProcessor<T> extends DropboxBaseProcessor<List<T>>   {
	
	public DropboxListModelProcessor(RequestDataWrapper dataWrapper, ResultReceiver resultReceiver) {
		super(dataWrapper, resultReceiver);

	}

	private static final String ARRAY = "contents";
	
	public List<T> toListModel(String source) throws Exception {
		if (source == null || source.length() == 0) {
			return null;
		}
		List<T> list = new ArrayList<T>();
		JSONObject object = new JSONObject(source);
		list.add(0, createModel(object));
		if(object.isNull(ARRAY)){
			return list;
		}
		JSONArray array = new JSONObject(source).getJSONArray(ARRAY);
		if (array.length() == 0) {
			return list;
		}
		for (int i = 0; i < array.length(); i++) {
			list.add(1, createModel(array.getJSONObject(i)));
		}
		return list;
	}
	
	public abstract T createModel(JSONObject jsonObject);
}